<?php
namespace app\admin\controller;

use app\admin\model\MajorModel;
use cmf\controller\AdminBaseController;
use app\admin\model\School as SchoolModel;
use think\db\Where;
use think\Validate;

class MajorController extends AdminBaseController {
    public function index() {
        extract(input());
        $where = new Where;
        if(isset($major_name) && !empty($major_name)){
            $where['major_name'] = ['like','%'.$major_name.'%'];
        }
        if(isset($school_id) && !empty($school_id)){
            $where['school_id'] = ['like','%'.$school_id.'%'];
        }
        $school = SchoolModel::all();
        $data = MajorModel::with('school')
            ->where($where)
            ->order('id Desc')
            ->paginate(3,false,['query'=>input()]);
        $page = $data->render();
        return $this->fetch('',[
            'data' => $data,
            'school'=>$school,
            'page' => $page,
        ]);
    }
    public function add(){
        $data = SchoolModel::all();
        return $this->fetch('',['data' => $data]);
    }
    public function addPost(){
        $data = input ();
        $add = MajorModel::create($data);
        if ($add) {
            return json(['code'=>1,'msg'=>'添加成功']);
        }else{
            return json(['code'=>2,'msg'=>'添加失败']);
        }
    }
    public function edit(){
        $id = input('id');
        $data = MajorModel::where('id',$id)->find();
        $user = SchoolModel::all();
        $this->assign('data',$data);
        $this->assign('id',$id);
        $this->assign('user',$user);

        return $this->fetch();
    }
    public function editPost(){
        $data = input();
        $rule = [
            'major_name'  => 'require',
        ];
        $msg = [
            'major_name.require' => '专业名称不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result  = $validate->check($data);
        if (true !== $result) {
            $this->error($validate->getError());
        }
        $edit = MAjorModel::where('id',$data['id'])->update($data);
        if($edit){
            return json(['code'=>1,'msg'=>'修改成功']);
        }else{
            return json(['code'=>2,'msg'=>'修改失败']);
        }
    }
    public function delete(){
        $id = input('id');
        $del  = MajorModel::destroy($id);
        if($del){
            return json(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json(['code'=>2,'msg'=>'删除失败']);
        }
    }
    public function delAll() {
        $ids = input('ids/a');
        $del = MajorModel::destroy($ids);
        if($del){
            $this->success('删除成功','Major/index');
        }else{
            $this->error('删除失败','Major/index');
        }
    }
}